import router from '@/router'
import store from '@/store';
import Cookies from 'js-cookie';

// 触发action 异步获取后端传递路由表
// store.dispatch('getRoutes');

let whiteList = ["/about", "/login"];

router.beforeEach(async (to, from, next) => {
  let token = Cookies.get('token');
  if(token) {
    if(to.path == "/login") { // 已登录，跳转登录页面
      next('/'); // 跳到首页
    } else {
      // 判断是否已经获取登录后的路由权限表
      if(store.state.asyncRoutes.length == 0) {
        const _asyncRoutes = await store.dispatch('getRoutes');
        _asyncRoutes.forEach(item => {
          router.addRoute(item);
        })
        next(to.path); // 在获取了权限路由表后，需要继续跳转，否则会卡在跳转路由的地方
      } else {
        if(to.matched.length !== 0) {
          next();
        } else {
          alert('当前用户无页面访问权限')
          next(from.path);
        }
      }
    }
  } else {
    if(whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next("/login");
    }
  }
})

